import { type SetupContext, type CSSProperties, type HTMLAttributes } from 'vue';

export interface IconProps extends HTMLAttributes{
    size?: number
    spin?: boolean
    rotate?: number
    prefixCls?: string
    type?: string
    color?: string
    strokeWidth?: number
}

const Icon = (props: IconProps, { slots }: SetupContext) => {
    const prefixCls = props.prefixCls ?? 'cui';
    const spin = props.spin ?? false;
    const type = props.type ?? '';
    const clazzList = () => {
        return {
            [`${prefixCls}-icon`]: true,
            [`${prefixCls}-icon-spinning`]: spin,
            [`${prefixCls}-icon-${type}`]: Boolean(type)
        };
    };
    const outerStyle: CSSProperties = {
    };
    if (Number.isSafeInteger(props.rotate)) {
        outerStyle.transform = `rotate(${props.rotate}deg)`;
    }
    if (Number.isSafeInteger(props.size)) {
        outerStyle['font-size'] = `${props.size}px`;
    }
    if (props.color) {
        outerStyle.color = props.color;
    }
    return <span aria-label={type} class={clazzList()} style={outerStyle}>{slots.default?.()}</span>;
};

const convertIcon = (Svg: any, iconType: string, type: string = 'outline', props: IconProps) => {
    const color = props.color ?? undefined;
    const style: any = {};
    if (type === 'twotone') {
        style['--cui-icon-twotone-primary'] = color ?? '#333';
    }

    const strokeProps: any = {};
    if (Number.isSafeInteger(props.strokeWidth)) {
        strokeProps['stroke-width'] = `${props.strokeWidth}px`;
    }

    return <Icon prefixCls="cui" type={iconType} {...props} color={color}>
        <Svg style={style} {...strokeProps}/>
    </Icon>;
};

export { convertIcon };
export default Icon;
